package org.carpediem.conman;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Mark Petrovic
 */
public class Util {
    private final static Logger logger = Logger.getLogger(Util.class.getName());

    private Util() {
    }

    public static String byteToHex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte aB : b) {
            sb.append(Integer.toString((aB & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    public static MessageDigest md5Instance() {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            // This will never happen with MD5
            e.printStackTrace();
        }
        return digest;
    }

    public static String hexDigest(String input) {
        MessageDigest digest = Util.md5Instance();
        byte[] buffer = null;
        try {
            buffer = digest.digest(input.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // will never happen with utf-8
            e.printStackTrace();
        }
        return Util.byteToHex(buffer);
    }

    public static String hexDigest(StringBuilder sb) {
        return Util.hexDigest(sb.toString());
    }

    public static String hexDigest(byte[] input) {
        MessageDigest digest = Util.md5Instance();
        byte[] buffer = digest.digest(input);
        return Util.byteToHex(buffer);
    }

    public static byte[] digest(byte[] input) {
        MessageDigest digest = Util.md5Instance();
        return digest.digest(input);
    }

    public static byte[] bytes(String s) {
        byte[] buffer = new byte[0];
        try {
            buffer = s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException wontHappen) {
            logger.log(Level.WARNING, "unsupported encoding", wontHappen);
        }

        return buffer;
    }
}
